import plugin from '../../../lib/plugins/plugin.js'
import { createRequire } from "module";
import fs from 'node:fs'
import command from '../model/command.js'
import puppeteer from '../../../lib/puppeteer/puppeteer.js'

//项目路径
const _cwdpath = process.cwd();

const require = createRequire(import.meta.url);

const { exec, execSync } = require("child_process");

let ing = {};
let isLW = false;

export class textrank extends plugin {
    constructor() {
        super({
            name: '群聊关键词提取',
            dsc: '群聊关键词提取',
            event: 'message',
            priority: 998,
            rule: [
                {
                    reg: '^#?(今日关键词|今日话痨|今日龙王)$',
                    fnc: 'dayrank',
                },
                {
                    reg: '^#?群大佬$',
                    fnc: 'qundalao',
                },
                {
                    reg: '^#?(清空|删除)关键词$',
                    fnc: 'deletrank',
                },
            ]
        })
    }
    async dayrank(e) {


        if (!this.e.msg.includes('关键词')) {
            isLW = true;
        } else {
            isLW = false;
        }

        if (ing[this.e.group_id]) {
            this.e.reply("正在分析聊天记录，请勿重复获取...稍等...");
            return true;
        }
        ing[this.e.group_id] = 1;
        this.e.reply("正在分析聊天记录，请稍后......");

        let today = new Date(new Date().toLocaleDateString()).getTime().toString().substring(0, 10);

        let detet = new Date();
        detet.setMinutes(0);
        detet.setSeconds(0);
        detet.setMilliseconds(0);
        let savadate = detet.getTime();

        let savepath = `${_cwdpath}/plugins/suiyue/resources/textranksave/save(${e.group_id})${savadate}.txt`
        let savepathLW = `${_cwdpath}/plugins/suiyue/resources/textranksave/saveLW(${e.group_id})${savadate}.txt`

        if (!fs.existsSync(savepath) || !fs.existsSync(savepathLW)) {
            fs.writeFileSync(savepath, "");
            fs.writeFileSync(savepathLW, "");

        } else {
            this.getExtract(isLW ? savepathLW : savepath);
            return true;
        }

        let CharHistory = await this.e.group.getChatHistory(0, 1);
        let seq = CharHistory[0].seq;

        let CharList = {};
        let allcount = 0;

        for (let i = seq; i > 0; i = i - 20) {
            let CharTemp = await this.e.group.getChatHistory(i, 20);


            if (CharTemp.length == 0) {
                break;
            }
            for (const key in CharTemp) {
                if (CharTemp[key].length == 0) {
                    continue;
                }
                if (CharTemp[key].user_id == Bot.uin) {
                    continue;
                }

                if (CharTemp[key].time < today /* && e.msg.includes("今日")*/) {
                    i = 0;
                    continue;
                }

                allcount++;

                let message = CharTemp[key].message;
                for (const msgkey in message) {
                    if (message[msgkey].type == 'text' && message[msgkey].text.match(/[\u4e00-\u9fa5]/g)) {
                        fs.appendFileSync(savepath, `${message[msgkey].text}。`, 'utf8');
                    }
                }

                //龙王
                if (CharList[CharTemp[key].user_id]) {
                    CharList[CharTemp[key].user_id].weight += 1;
                    CharList[CharTemp[key].user_id].word = await this.replaceStr(CharTemp[key].sender.card ? CharTemp[key].sender.card : CharTemp[key].sender.nickname);
                } else {
                    CharList[CharTemp[key].user_id] = {
                        weight: 1,
                        // user_id: CharTemp[key].user_id,
                        word: await this.replaceStr(CharTemp[key].sender.card ? CharTemp[key].sender.card : CharTemp[key].sender.nickname)
                    };
                }
            }

        }

        let CharArray = [];
        for (const key in CharList) {
            CharArray.push(CharList[key]);
        }
        fs.appendFileSync(savepathLW, JSON.stringify(CharArray), 'utf8');



        this.getExtract(isLW ? savepathLW : savepath);

        return true; //返回true 阻挡消息不再往下
    }
    async getExtract(savepath) {

        let content = fs.readFileSync(savepath, 'utf8');

        let chartData;

        if (isLW) {
            chartData = content;
        } else {
            var nodejieba = require("nodejieba");
            var topN = 88;
            chartData = await nodejieba.extract(content, topN);
            chartData = JSON.stringify(chartData);
        }

        let imgdata = await command.getData("textrank",
            {
                chartData
            });
        /** 生成图片 */
        let img = await puppeteer.screenshot('textrank', imgdata);
        if (img) await this.e.reply(img);

        ing[this.e.group_id] = 0;

    }
    /**
     * 
     * @param e oicq传递的事件参数e
     */
    async qundalao() {

        if (!this.e.isGroup) {
            return false;
        }

        let mmap = await this.e.group.getMemberMap();

        let members = Array.from(mmap.values());

        members.sort((a, b) => {
            return a.join_time - b.join_time
        })

        members = members.slice(0, 60)
        let res = [];
        for (let v of members) {

            let restemp = { weight: await this.time2str(v.join_time), word: await this.replaceStr(v.card ? v.card : v.nickname) };

            res.push(restemp);
        }

        let chartData = JSON.stringify(res);

        let imgdata = await command.getData("textrank",
            {
                chartData
            });
        /** 生成图片 */
        let img = await puppeteer.screenshot('textrank', imgdata);
        if (img) await this.reply(img);

        return true;

    }
    async time2str(timestamp) {
        let now = Date.now()
        if (timestamp < 0xffffffff)
            timestamp *= 1000
        let time = Math.floor(Math.abs(now - timestamp) / 1000)
        if (time >= 86400)
            time = Math.floor(time / 86400)
        else
            time = 0
        return time
    }
    async replaceStr(str) {

        // console.log("name:",str,"\n");
        // let temp = JSON.stringify(str);
        // console.log("JSONname:",temp,"\n");
        // let rstr = temp.replace(/\\|\/|\'|\"|\‘|\“|\n|\r|"|'|”|’|{|}/gm, '')
        // console.log("replacename:",rstr,"\n");

        let rstr = str.replace(/\\|\/|\'|\"|\‘|\“|\n|\r|"|'|”|’|{|}/gm, '')

        return rstr;
    }

    /**
     * 
     * @param e oicq传递的事件参数e
     */
    async deletrank() {

        let savepath = `${_cwdpath}/plugins/suiyue/resources/textranksave/`

        let command = "du -h";
        let fileSize = "0k";
        var ls = exec(command, { cwd: savepath }, async function (error, stdout, stderr) {
            if (error) {
                me.e.reply(`出错了，尝试手动处理${savepath}下的文件吧`);
            } else {
                fileSize = stdout;
            }
        });

        command = "rm -rf *.txt";

        ls = exec(command, { cwd: savepath }, async function (error, stdout, stderr) {
            if (error) {
                this.e.reply(`出错了，尝试手动处理${savepath}下的文件吧`);
            } else {
                this.e.reply(`清除成功,共清理${fileSize.trim()}文件`);
            }
        });

    }


}